package com.mybatis.dao;

import com.mybatis.pojo.Flysysuser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Pretty·Boy
 * @date 2018/12/16 14:53
 */
public class UserDaoImpl implements UserDao {

    private SqlSessionFactory sqlSessionFactory;

    //注入sqlSessionFactory
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }


    public Flysysuser getUserByid() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Flysysuser flysysuser = new Flysysuser();
        try {
            flysysuser = sqlSession.selectOne("getUserById", 9);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSessionFactory.getClass();
            }
        }
        return flysysuser;
    }

    /**
     * 获取SqlSession
     */
    private static SqlSession getSqlSession() throws IOException {
        //创建SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //使用Mybatis提供的Resource工具类，加载properties属性文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        //创建SqlSession工厂
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        //获取SqlSession
        return sqlSessionFactory.openSession();
    }
}
